package org.amicofragile.calculator

abstract class Tree {
	type Environment = String => Int
	
	def eval(t: Tree, env: Environment): Int = t match {
		case Sum(l, r) => eval(l, env) + eval(r, env)
		case Diff(l, r) => eval(l, env) - eval(r, env)
		case Var(n)	=> env(n)
		case Const(k) => k
	}
	
	def derive(t: Tree, v: String): Tree = t match {
		case Sum(l, r) => Sum(derive(l, v), derive(r, v))
		case Diff(l, r) => Diff(derive(l, v), derive(r, v))
		case Var(n) if (v == n) => Const(1)
		case _ => Const(0)
	}

}

case class Var(n: String) extends Tree {
}

case class Sum(l: Tree, r: Tree) extends Tree {
}

case class Diff(l: Tree, r: Tree) extends Tree {
}

case class Const(v: Int) extends Tree {
}